package com.xb.chain.dao;

import com.xb.chain.constant.InfoConstant;
import com.xb.chain.entity.ConnectionInfo;
import com.xb.chain.utils.JdbcUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class HostInfoDao {

    /**
     * 插入一条Ip、port记录
     */
    public static int insert(ConnectionInfo connectionInfo){
        Connection connection = JdbcUtil.getConnection();
        Statement statement = null;
        try {
            statement = connection.createStatement();
            String sql = "insert into t_host_info(ip_port,host_ip,host_port) values('"+connectionInfo.getIp()+":"+connectionInfo.getPort()+"','"+connectionInfo.getIp()+"','"+connectionInfo.getPort()+"') ON DUPLICATE KEY UPDATE host_ip='"+connectionInfo.getIp()+"',host_port='"+connectionInfo.getPort()+"'";
            return statement.executeUpdate(sql);
        } catch (SQLException e) {
            log.error("host_info插入记录失败:{}",e);
        }finally {
            JdbcUtil.closeConnection(statement);
        }
        return 0;
    }

    /**
     *  查询所有节点信息
     */
    public static List<ConnectionInfo> getNodeList(){
        Connection connection = JdbcUtil.getConnection();
        Statement statement = null;
        ResultSet resultSet = null;
        List<ConnectionInfo> list = new ArrayList<>();
        try {
            statement = connection.createStatement();
            String sql = "select * from t_host_info";
            resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                String hostIp = resultSet.getString("host_ip");
                Integer hostPort = Integer.valueOf(resultSet.getString("host_port"));
                list.add(ConnectionInfo.builder().ip(hostIp).port(hostPort).build());
            }
        } catch (SQLException e) {
            log.error("host_info插入记录失败:{}",e);
        }finally {
            JdbcUtil.closeConnection(statement,resultSet);
        }
        return list;
    }




}
